package net.taviscaron.drivenotes.api.action;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.taviscaron.drivenotes.api.ApiError;
import net.taviscaron.drivenotes.api.ResponseUtil;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.ChargingService;
import net.taviscaron.drivenotes.shared.service.GarageService;
import net.taviscaron.drivenotes.web.core.Constants;
import org.springframework.beans.factory.annotation.Required;

/**
 * Charging action
 * @author Andrei Senchuk
 */
public class ChargingAction implements ApiAction {
    private ChargingService chargingService;
    private GarageService garageService;

    @Required
    public void setGarageService(GarageService garageService) {
        this.garageService = garageService;
    }

    @Required
    public void setChargingService(ChargingService chargingService) {
        this.chargingService = chargingService;
    }

    public Object execute (HttpServletRequest request, HttpServletResponse response) {
        Long carId = null;
        try {
            String stringCarId = request.getParameter("carId");
            carId = Long.valueOf(stringCarId);
        } catch (Exception e) {
            return ResponseUtil.errorResponse(ApiError.BAD_REQUEST, "car id not specified or it's not a number");
        }

        User user = (User)request.getAttribute(Constants.AUTHORIZED_USER_ATTR_NAME);
        List<Car> cars = garageService.findCarsByOwnerId(user.getId());
        Car car = null;

        for(Car c : cars) {
            if(carId.equals(c.getId())) {
                car = c;
                break;
            }
        }

        if(car != null) {
            return ResponseUtil.successResponse("charging", chargingService.findChargingsByCar(car));
        } else {
            return ResponseUtil.errorResponse(ApiError.BAD_REQUEST, "no such car");
        }
    }
}
